import { userApi } from '@/api'

// 用户模块状态管理
const state = {
  // 用户信息
  userInfo: null,
  // 登录状态
  isLoggedIn: false,
  // 登录token
  token: localStorage.getItem('token') || null,
  // 用户权限
  permissions: []
}

const mutations = {
  // 设置用户信息
  SET_USER_INFO(state, userInfo) {
    state.userInfo = userInfo
    state.isLoggedIn = !!userInfo
  },
  
  // 设置token
  SET_TOKEN(state, token) {
    state.token = token
    if (token) {
      localStorage.setItem('token', token)
    } else {
      localStorage.removeItem('token')
    }
  },
  
  // 设置用户权限
  SET_PERMISSIONS(state, permissions) {
    state.permissions = permissions
  },
  
  // 清除用户信息
  CLEAR_USER_INFO(state) {
    state.userInfo = null
    state.isLoggedIn = false
    state.token = null
    state.permissions = []
    localStorage.removeItem('token')
  }
}

const actions = {
  // 用户登录
  async login({ commit }, { username, password }) {
    try {
      const response = await userApi.login({ username, password })
      
      if (response.code === 200) {
        const { user, token } = response.data
        
        // 保存到localStorage
        localStorage.setItem('token', token)
        localStorage.setItem('userInfo', JSON.stringify(user))
        
        commit('SET_USER_INFO', user)
        commit('SET_TOKEN', token)
        commit('SET_PERMISSIONS', ['read', 'write'])
        
        return { success: true, message: '登录成功' }
      } else {
        return { success: false, message: response.message }
      }
    } catch (error) {
      return { success: false, message: error.message || '登录失败' }
    }
  },
  
  // 用户注册
  async register({ commit }, { username, email, password }) {
    try {
      const response = await userApi.register({ username, email, password })
      
      if (response.code === 200) {
        const { user, token } = response.data
        
        // 保存到localStorage
        localStorage.setItem('token', token)
        localStorage.setItem('userInfo', JSON.stringify(user))
        
        commit('SET_USER_INFO', user)
        commit('SET_TOKEN', token)
        commit('SET_PERMISSIONS', ['read', 'write'])
        
        return { success: true, message: '注册成功' }
      } else {
        return { success: false, message: response.message }
      }
    } catch (error) {
      return { success: false, message: error.message || '注册失败' }
    }
  },
  
  // 用户登出
  logout({ commit }) {
    commit('CLEAR_USER_INFO')
    return { success: true, message: '登出成功' }
  },
  
  // 检查认证状态
  async checkAuthStatus({ commit, state }) {
    if (state.token) {
      try {
        const response = await userApi.getUserInfo()
        
        if (response.code === 200) {
          commit('SET_USER_INFO', response.data)
          commit('SET_PERMISSIONS', ['read', 'write'])
        } else {
          // token无效，清除用户信息
          commit('CLEAR_USER_INFO')
        }
      } catch (error) {
        // token无效，清除用户信息
        commit('CLEAR_USER_INFO')
      }
    }
  },
  
  // 更新用户信息
  async updateUserInfo({ commit, state }, userInfo) {
    try {
      const response = await userApi.updateUserInfo(userInfo)
      
      if (response.code === 200) {
        commit('SET_USER_INFO', { ...state.userInfo, ...userInfo })
        return { success: true, message: '更新成功' }
      } else {
        return { success: false, message: response.message }
      }
    } catch (error) {
      return { success: false, message: error.message || '更新失败' }
    }
  }
}

const getters = {
  // 获取用户信息
  userInfo: state => state.userInfo,
  
  // 获取登录状态
  isLoggedIn: state => state.isLoggedIn,
  
  // 获取token
  token: state => state.token,
  
  // 获取用户权限
  permissions: state => state.permissions,
  
  // 检查是否有特定权限
  hasPermission: (state) => (permission) => {
    return state.permissions.includes(permission)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
} 